/*
 * Copyright 2010 Dovado FZ-LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.dovado.dovadoremote;

import java.util.ArrayList;
import java.util.StringTokenizer;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.TextView;

public class Info extends Activity {
	static ArrayList<String> infoList = new ArrayList<String>();
	static ArrayList<TextView> infoTexts = new ArrayList<TextView>();

	/*
	 * Get GPS latitude.
	 */
	public static int getGPSLat() {
		int i = 0;
		setIsBogusCoordinates(false);
		while (i < infoList.size()) {
			if (infoList.get(i).indexOf("GPS_LAT") != -1) {
				StringTokenizer st = new StringTokenizer(infoList.get(i), "=");
				while (st.hasMoreTokens()) {
					st.nextToken();
					String val = st.nextToken();
					/*
					 * remove first and last character if <'> is found
					 */
					if (val.substring(0, 1).equalsIgnoreCase("'")) {
						val = val.substring(1, val.length() - 1);
					}

					/*
					 * default answer =17
					 */
					Double answer = 17.0;

					try {
						answer = Double.parseDouble(val);
					} catch (NumberFormatException e) {
						setIsBogusCoordinates(true);
						e.printStackTrace();
					}
					answer = (answer * 1E6);
					return answer.intValue();
				}
			}
			i++;
		}
		/*
		 * default
		 */
		setIsBogusCoordinates(true);
		System.err.println("returning bogus LAT: 17");
		return 17;
	}

	/*
	 * get gps longitude:
	 */
	public static int getGPSLong() {
		int i = 0;
		setIsBogusCoordinates(false);
		while (i < infoList.size()) {
			if (infoList.get(i).indexOf("GPS_LONG") != -1) {
				StringTokenizer st = new StringTokenizer(infoList.get(i), "=");
				while (st.hasMoreTokens()) {
					st.nextToken();
					String val = st.nextToken();
					/*
					 * remove first and last character if <'> is found
					 */
					if (val.substring(0, 1).equalsIgnoreCase("'")) {
						val = val.substring(1, val.length() - 1);
					}
					Double answer = 17.0;
					try {
						answer = Double.parseDouble(val);
					} catch (NumberFormatException e) {
						e.printStackTrace();
						setIsBogusCoordinates(true);
					}
					answer = (answer * 1E6);
					return answer.intValue();
				}
			}
			i++;
		}
		setIsBogusCoordinates(true);
		// default
		System.err.println("returning bogus long 17");
		return 17;
	}

	/*
	 * Did we put bogus-parameters?
	 */
	public static boolean getIsBogusCoordinates() {
		return isBogusCoordinates;
	}

	public static void setIsBogusCoordinates(boolean inIsBogusCoordinates) {
		isBogusCoordinates = inIsBogusCoordinates;
	}

	LinearLayout lx;

	/*
	 * A string which contain the "Not available"-message
	 */
	private static String naString;

	/*
	 * Did we get true coordinates? used in map-class
	 */
	private static boolean isBogusCoordinates;

	/*
	 * Get info such as (DATE= , TIME= or SIGNAL_STRENGTH=)
	 */
	public static String parseInfo(String inString) {
		String tmpEntry;
		int i = 0;
		while (i < infoList.size()) {
			tmpEntry = infoList.get(i);
			// if we find the string we're looking for then return the value of
			// that key:
			if (tmpEntry.contains(inString)) {
				return infoList.get(i).substring(inString.length());
			}
			i++;
		}

		return naString;
	}

	/*
	 * TODO: remove this.
	 */
	protected void alertbox(String title, String mymessage) {
		new AlertDialog.Builder(this).setMessage(mymessage).setTitle(title)
				.setCancelable(true).setNeutralButton(android.R.string.ok,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int whichButton) {
							}
						}).show();
	}

	/*
	 * create array of info locally
	 */
	public void createInfoList(ArrayList<String> tmpInfoList) {
		infoList = tmpInfoList;
	}

	/*
	 * put the info on screen
	 */
	void initialize(String in_from) {
		/*
		 * If a value is missing (for example signal strength) then show.. :
		 */
		naString = getResources().getString(R.string.na);

		LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
		lx = (LinearLayout) findViewById(R.id.LinearLayoutInfo);
		lx.removeAllViews();
		/*
		 * Remove all objects from view on update:
		 */
		infoTexts.clear();
		lx.setOrientation(LinearLayout.VERTICAL);

		/*
		 * show welcome-message if no info is available:
		 */
		if (infoList.size() == 0) {
			/*
			 * if (in_from.contains("fromresume")){ alertbox("Not available",
			 * getResources().getString(R.string.infodefault)); }
			 */
			infoTexts.add(new TextView(this));
			infoTexts.get(0).setTextColor(
					getResources().getColor(R.color.bodytext));
			infoTexts.get(0).setText(
					getResources().getString(R.string.infodefault));
			infoTexts.get(0).setWidth(
					getWindowManager().getDefaultDisplay().getWidth());
			try {
				lx.addView(infoTexts.get(0), layoutParams);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		int i = 0;

		/*
		 * parse all values from the list of info. Here you can make whatever
		 * you want with the info (such a graphics for the signal strength etc)
		 */
		if (infoList.size() > 3) {
			infoTexts.add(new TextView(this));
			infoTexts.get(i).setText("General");
			infoTexts.get(i).setTextAppearance(this, R.style.infolabels);

			// Set one of the textviews to fit screen for layout:
			infoTexts.get(i).setWidth(
					getWindowManager().getDefaultDisplay().getWidth());
			i++;

			infoTexts.add(new TextView(this));
			infoTexts.get(i).setTextAppearance(this, R.style.small_infotext);
			infoTexts.get(i).setText(
					"Router Firmware: " + parseInfo(">> Firmware_Revision:"));
			i++;

			infoTexts.add(new TextView(this));
			infoTexts.get(i).setTextAppearance(this, R.style.small_infotext);
			infoTexts.get(i).setText(
					"API Version: " + parseInfo("API_version:"));
			i++;

			infoTexts.add(new TextView(this));
			infoTexts.get(i).setTextAppearance(this, R.style.small_infotext);
			infoTexts.get(i).setText(
					"Product Name: " + parseInfo("PRODUCT_NAME="));
			i++;
			// -----------------------
			infoTexts.add(new TextView(this));
			infoTexts.get(i).setTextAppearance(this, R.style.infolabels);
			infoTexts.get(i).setText("Connections");
			i++;

			infoTexts.add(new TextView(this));
			infoTexts.get(i).setTextAppearance(this, R.style.small_infotext);
			infoTexts.get(i).setText(
					"Current connection type: " + parseInfo("CONNECTION="));
			i++;

			infoTexts.add(new TextView(this));
			infoTexts.get(i).setTextAppearance(this, R.style.small_infotext);
			infoTexts.get(i).setText(
					"External IP address: " + parseInfo("EXTERNAL_IP="));
			i++;

			infoTexts.add(new TextView(this));
			infoTexts.get(i).setTextAppearance(this, R.style.small_infotext);
			String sigStrength = parseInfo("SIGNAL_STRENGTH=");
			int sigInt;
			try {
				sigInt = Integer.parseInt(sigStrength);
			} catch (Exception e) {
				// if we get a numberException, set signal to -1
				sigInt = -1;
			}
			if (sigInt != -1) {
				sigStrength = sigStrength + "%";
			} else {
				sigStrength = naString;
			}
			infoTexts.get(i).setText("Modem signal strength: " + sigStrength);
			i++;
			// ----------------------
			infoTexts.add(new TextView(this));
			infoTexts.get(i).setText("Traffic");
			infoTexts.get(i).setTextAppearance(this, R.style.infolabels);
			i++;

			infoTexts.add(new TextView(this));
			infoTexts.get(i).setTextAppearance(this, R.style.small_infotext);
			try {
				infoTexts
						.get(i)
						.setText(
								"Transmitted Modem: "
										+ (Integer
												.parseInt(parseInfo("TRAFFIC_MODEM_TX=")) / 1000)
										+ " MB");
			} catch (NumberFormatException e) {
				infoTexts.get(i).setText("Transmitted Modem: Not available");
			}
			i++;

			infoTexts.add(new TextView(this));
			infoTexts.get(i).setTextAppearance(this, R.style.small_infotext);
			try {
				infoTexts
						.get(i)
						.setText(
								"Received Modem: "
										+ (Integer
												.parseInt(parseInfo("TRAFFIC_MODEM_RX=")) / 1000)
										+ " MB");
			} catch (NumberFormatException e) {
				infoTexts.get(i).setText("Received Modem: Not available");
			}
			i++;

			infoTexts.add(new TextView(this));
			infoTexts.get(i).setTextAppearance(this, R.style.small_infotext);
			try {
				infoTexts
						.get(i)
						.setText(
								"Transmitted Ethernet: "
										+ (Integer
												.parseInt(parseInfo("TRAFFIC_WAN_TX=")) / 1000)
										+ " MB");
			} catch (NumberFormatException e) {
				infoTexts.get(i).setText("Transmitted Ethernet: Not available");
			}
			i++;

			infoTexts.add(new TextView(this));
			infoTexts.get(i).setTextAppearance(this, R.style.small_infotext);
			try {
				infoTexts
						.get(i)
						.setText(
								"Received Ethernet: "
										+ (Integer
												.parseInt(parseInfo("TRAFFIC_WAN_RX=")) / 1000)
										+ " MB");
			} catch (NumberFormatException e) {
				infoTexts.get(i).setText("Received Ethernet: Not available");
			}
			i++;

			// ----------------
			infoTexts.add(new TextView(this));
			infoTexts.get(i).setText("Positioning");
			infoTexts.get(i).setTextAppearance(this, R.style.infolabels);
			i++;

			infoTexts.add(new TextView(this));
			infoTexts.get(i).setTextAppearance(this, R.style.small_infotext);
			String positioningType = parseInfo("GPS_TYPE=");
			if (!positioningType.contains(naString)
					&& !positioningType.contains("OFF")) {
				infoTexts.get(i).setText(
						"Positioning type: " + parseInfo("GPS_TYPE="));
				i++;

				infoTexts.add(new TextView(this));
				infoTexts.get(i)
						.setTextAppearance(this, R.style.small_infotext);
				infoTexts.get(i).setText("Latitude: " + parseInfo("GPS_LAT="));
				i++;

				infoTexts.add(new TextView(this));
				infoTexts.get(i)
						.setTextAppearance(this, R.style.small_infotext);
				infoTexts.get(i)
						.setText("Longitude: " + parseInfo("GPS_LONG="));
				i++;

				infoTexts.add(new TextView(this));
				infoTexts.get(i)
						.setTextAppearance(this, R.style.small_infotext);
				infoTexts.get(i)
						.setText(
								"Sunrise at current position: "
										+ parseInfo("SUNRISE="));
				i++;

				infoTexts.add(new TextView(this));
				infoTexts.get(i)
						.setTextAppearance(this, R.style.small_infotext);
				infoTexts.get(i).setText(
						"Sunset at current position: " + parseInfo("SUNSET="));
				i++;
			} else {
				infoTexts.get(i).setText(naString);
				i++;
			}

			// -----------------
			infoTexts.add(new TextView(this));
			infoTexts.get(i).setText("Misc");
			infoTexts.get(i).setTextAppearance(this, R.style.infolabels);
			i++;

			infoTexts.add(new TextView(this));
			infoTexts.get(i).setTextAppearance(this, R.style.small_infotext);
			infoTexts.get(i).setText("Current date: " + parseInfo("DATE="));
			i++;

			infoTexts.add(new TextView(this));
			infoTexts.get(i).setTextAppearance(this, R.style.small_infotext);
			infoTexts.get(i).setText("Current time: " + parseInfo("TIME="));
			i++;

			infoTexts.add(new TextView(this));
			infoTexts.get(i).setTextAppearance(this, R.style.small_infotext);
			infoTexts.get(i).setText(
					"Number of unread SMS: " + parseInfo("SMS_UNREAD="));
			i++;

			infoTexts.add(new TextView(this));
			infoTexts.get(i).setTextAppearance(this, R.style.small_infotext);
			infoTexts.get(i).setText(
					"Number of SMS in inbox: " + parseInfo("SMS_TOTAL="));
			i++;

			infoTexts.add(new TextView(this));
			infoTexts.get(i).setTextAppearance(this, R.style.small_infotext);
			infoTexts.get(i).setText(
					"Connected devices: " + parseInfo("CONNECTED_DEVICES="));
			i++;
		}

		i = 0;
		/*
		 * for each info-line, add a textfield:
		 */
		while (i < infoTexts.size()) {
			infoTexts.get(i).setTextColor(
					getResources().getColor(R.color.bodytext));
			try {
				lx.addView(infoTexts.get(i), layoutParams);
			} catch (Exception e) {
				e.printStackTrace();
			}

			i++;
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.info);
		initialize("fromcreate");
	}

	/*
	 * If the user presses the 'back'-button (we can add some more functionality
	 * here
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			Intent i = new Intent();
			i.setAction(Intent.ACTION_MAIN);
			i.addCategory(Intent.CATEGORY_HOME);
			this.startActivity(i);
			return true;
		}
		return false;
	}

	/*
	 * TODO: remove this
	 */
	@Override
	public void onPause() {
		super.onPause();
	}

	/*
	 * Re-initialize when we resume
	 */
	@Override
	public void onResume() {
		super.onResume();

		initialize("fromresume");

	}

	/*
	 * Standard window-focus override. Notice focus lost so we can pause on
	 * focus lost. e.g. user switches to take a call.
	 */
	@Override
	public void onWindowFocusChanged(boolean hasWindowFocus) {
		if (hasWindowFocus) {
			initialize("focuschanged");
		}
	}

	/*
	 * Removes everything drawn. Needed when switching views etc
	 */
	public void removeAll() {
		infoList.clear();
		infoTexts.clear();
	}
}